package com.bac.rentmap.web.controller.osmimport;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.bac.rentmap.model.Building;

public class BuildingDataSyncController extends AbstractController {
    private PersistenceManagerFactory persistenceManagerFactory;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        int startIndex = Integer.parseInt(request.getParameter("start"));
        PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
        try{
            Query query = persistenceManager.newQuery(Building.class);
            //query.setFilter("lowercaseStreetCalculated != true");
            query.setRange(startIndex, startIndex + 1000);
            List<Building> buildings = (List<Building>) query.execute();
            for (Building building : buildings) {
                building.setStreet(building.getStreet());
                building.setVersion(1);
            }
            response.getWriter().print("Processed " + buildings.size() + " buildings");
        }
        finally{
            persistenceManager.close();
        }
        return null;
    }

    @Required
    public void setPersistenceManagerFactory(
            PersistenceManagerFactory persistenceManagerFactory) {
        this.persistenceManagerFactory = persistenceManagerFactory;
    }
}
